<template>
  <view class="update-content">
    <view v-if="!onlyShow" class="update-btn">
      <u-button type="primary" @click="showSheet">上传附件</u-button>
    </view>
    <view class="file-list">
      <fileItem
        v-for="item in fileList"
        :key="item.uid"
        :onlyShow="onlyShow"
        :item="item"
        @remove="remove"
      ></fileItem>
    </view>
  </view>

  <!--选择文件类型-->
  <u-action-sheet
    :list="list"
    v-model="show"
    :safe-area-inset-bottom="true"
    @click="actionSheetCallback"
  ></u-action-sheet>
</template>
<script lang="ts" setup>
import { useUserStoreWidthOut } from '@/stores/user';
import { getBaseUrl } from '@/utils/env';
import fileItem from './fileItem.vue';

const emits = defineEmits(['update:modelValue']);
const props = defineProps<{
  modelValue: any[];
  onlyShow?: boolean;
  limit?: number;
  accept?: string[];
}>();

const { modelValue, limit, accept } = toRefs(props);
const fileList = computed(() => modelValue.value || []);
const useUser = useUserStoreWidthOut();
const list = [
  {
    text: '所有类型',
  },
  {
    text: '图片',
  },
];
const show = ref(false);
const showSheet = () => {
  if (limit?.value && fileList.value.length === limit.value) {
    uni.showToast({
      title: `最多支持上传${limit.value}个文件`,
      icon: 'none',
      duration: 2000,
    });
    return;
  }
  show.value = true;
};
// 选择文件
const actionSheetCallback = (index: number) => {
  if (index === 0) {
    uni.chooseMessageFile({
      count: 1, //默认100
      type: 'all',
      success: function (res) {
        console.log(JSON.stringify(res.tempFiles));
        uploadFile(res);
      },
    });
  } else {
    uni.chooseMedia({
      count: 1, //默认100
      mediaType: ['image'],
      sizeType: ['original', 'compressed'],
      success: function (res) {
        console.log(JSON.stringify(res.tempFiles));
        uploadFile(res);
      },
    });
  }
};
// 格式化文件格式
function setTypes(typesStr: string[]) {
  typesStr = typesStr || [];
  let arr: string[] = [];
  typesStr.forEach((item) => {
    const type = item.split('/');
    arr = arr.concat(type);
  });
  return arr;
}
// 上传文件
const uploadFile = (data: any) => {
  console.log(data);
  const file = data.tempFiles[0];
  console.log('file', file);
  if (
    accept?.value &&
    accept.value.length > 0 &&
    !setTypes(accept.value).includes(
      (file.path || file.tempFilePath).split('.')[1]
    )
  ) {
    uni.showToast({
      title: `文件类型错误，请上传${accept?.value.join(',')}类型的文件`,
      icon: 'none',
      duration: 2000,
    });
    return;
  }
  uni.uploadFile({
    url: `${getBaseUrl()}/doc/Rest/doc/file/minioDocUpload/false`,
    filePath: file.path || file.tempFilePath,
    name: 'file',
    header: {
      'yootrial-account': '0',
      'yootrial-app': '0',
      'yootrial-timestamp': Date.now(),
      'yootrial-signature': '0',
      Authorization: useUser.getToken,
    },
    formData: {
      savePath: '目录01',
      bucket: 'yootrial-ctms',
    },
    success: (uploadFileRes) => {
      const data: any = JSON.parse(uploadFileRes.data);
      if (data.code === 'A00000') {
        fileList.value.push({
          uid: data.data,
          name:
            file.name ||
            `${data.data}.${(file.path || file.tempFilePath).split('.')[1]}`,
          size: file.size,
        });
        emits('update:modelValue', fileList.value);
      } else {
        uni.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000,
        });
      }
      console.log(uploadFileRes.data);
    },
  });
};

// 删除
const remove = (item: any) => {
  const index = fileList.value.findIndex((el) => el.uid === item.uid);
  if (index > -1) {
    fileList.value.splice(index, 1);
  }
};
</script>
